<?php
//PingBuWang.Com
//Copyright (c) 2017~2099 http://www.pingbuwang.com All rights reserved.
namespace app\xiongzhang\controller;
use think\Log;
use think\Request;
use mip\Init;
class ApiUserXiongZhang extends Init
{
    private $keyInfo;

    // 只是配置了一个自动回复功能
    public function configAccess()
    {
        $TOKEN = db('xiongzhangKey')->where('key','baiduXZToken')->find()['val'];
        $strSignature = getSHA1($TOKEN, $_GET['timestamp'], $_GET['nonce']);
        if ($strSignature == $_GET['signature']) {
            $accessToken = model('app\xiongzhang\model\xiongZhang')->getAccessToken();
            $inputInfo = file_get_contents('php://input');

            if(strpos($inputInfo,"<")===0){
                $baiduData = simplexml_load_string($inputInfo);
            }

            $baiduData = json_decode($inputInfo,true);


            // Log::alert($baiduData);

            //  array (
            //  'Content' => '你好',
            //  'MsgId' => 1557912359769225,
            //  'ToUserName' => 1590894693830359,
            //  'FromUserName' => '34gJWzAu7g-Z4euLCgc0XPn80',
            //  'CreateTime' => 1557912359,
            //  'MsgType' => 'text',
            //)

            $replyData = null;
            $autoReplyList = db('XiongzhangAutoReply')->select();
            if ($autoReplyList) {
                $msgContent = $baiduData['Content'];


                foreach ($autoReplyList as $key => $val) {
                    if (strpos($val['user_content'],$msgContent)!==false ) {
                        $replyData = $val;
                        break;
                    }
                }
            }
            if ($replyData) {
                $fromUserName = $baiduData['FromUserName'];
                $postArray = array(
                    "touser" => $fromUserName,
                    "msgtype" => "text",
                    "text" => array("content" => $replyData['reply_content'])
                );
                $subUrl = 'https://openapi.baidu.com/rest/2.0/cambrian/message/custom_send?access_token=' . $accessToken; 
                $replyStatus = getData($subUrl,json_encode($postArray));
            }
            
            // file_put_contents(ROOT_PATH."log.txt",$biaduData->Content);
            echo $_GET['echostr'];
        } else {
            echo 'failed';
        }
    }
    
}